package com.liuyk.commonlib.utility;

import android.os.Handler;
import android.os.Looper;

import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程池，建议不要直接new Thread，使用统一线程池，统一管理
 * <p>
 * Created by liuyakui on 2020/1/18.
 */
public final class ThreadPoolUtils {
    private static final int CORE_POOL_SIZE = 1;
    private static final int MAXIMUM_POOL_SIZE = 20;
    private static final int KEEP_ALIVE_SECONDS = 3;

    private static final Executor THREAD_POOL_EXECUTOR;

    private ThreadPoolUtils() {

    }

    public static ThreadPoolUtils getInstance() {
        return Inner.INSTANCE;
    }

    static {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(), new MyThreadFactory());
        new ThreadPoolExecutor.DiscardPolicy();
        THREAD_POOL_EXECUTOR = threadPoolExecutor;
    }

    public void executor(Runnable runnable) {
        if (runnable != null) {
            THREAD_POOL_EXECUTOR.execute(runnable);
        }
    }

    public void executorUIThread(Runnable runnable) {
        if (runnable != null) {
            new Handler(Looper.getMainLooper()).post(runnable);
        }
    }

    static class MyThreadFactory implements ThreadFactory {

        private final AtomicInteger mCount = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "JFTask: " + mCount.getAndIncrement());
        }
    }

    private static class Inner {
        private static final ThreadPoolUtils INSTANCE = new ThreadPoolUtils();
    }
}
